package org.msb.lock;


import lombok.extern.slf4j.Slf4j;
import org.apache.zookeeper.ZooKeeper;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.msb.unconf.DefaultWatch;
import org.msb.unconf.ZKConf;
import org.msb.unconf.ZKUtils;

import java.util.concurrent.CountDownLatch;

/**
 * @author: 马士兵教育
 * @create: 2019-09-20 16:14
 */
@Slf4j
public class TestLock {


    ZooKeeper zk;
    ZKConf zkConf;
    DefaultWatch defaultWatch;

    @Before
    public void conn(){
        zkConf = new ZKConf();
        zkConf.setAddress("39.105.11.10:2181/testLock");
        zkConf.setSessionTime(1000);
        defaultWatch = new DefaultWatch();
        ZKUtils.setConf(zkConf);
        ZKUtils.setWatch(defaultWatch);
        zk = ZKUtils.getZK();
    }

    @After
    public void close(){
        log.info("关闭 zk socket");
        ZKUtils.closeZK();
    }

    @Test
    public void testlock(){
        CountDownLatch countDownLatch = new CountDownLatch(10);


        for (int i = 0; i < 10; i++) {
           Thread thread = new Thread(()->{
                   WatchCallBack watchCallBack = new WatchCallBack();
            watchCallBack.setZk(zk);
            String name = Thread.currentThread().getName();
            watchCallBack.setThreadName(name);

            try {
                //tryLock
                watchCallBack.tryLock();
                System.out.println(name + " at work");
                watchCallBack.getRootData();
                // 获取到锁之后做操作
                Thread.sleep(3000);
                //unLock
                watchCallBack.unLock();
                countDownLatch.countDown();
            } catch (Exception e) {
                e.printStackTrace();
            }
           });

           thread.start();

        }
        try {
            countDownLatch.await();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }
}
